from flask import Flask, render_template, request, redirect, send_file
import requests
import os
import bot_process
from drifting_bottle_bot import bot_init, bot_quit
from drifting_bottle_bot_sql import bot_sql_init, bot_sql_quit
import signal
import sys

app = Flask(__name__)  # 创建app对象

# 设置配置
SOURCE_FOLDER = os.path.join(app.root_path, 'static', 'src')    # 图片资源
app.config['SOURCE_FOLDER'] = SOURCE_FOLDER
BOT_MODEL_FOLDER = os.path.join(app.root_path, 'static', 'model')   # 漂流瓶机器人模型
app.config['BOT_MODEL_FOLDER'] = BOT_MODEL_FOLDER
# 注册路由和其他配置
app.register_blueprint(bot_process.blueprint)  # 图片识别蓝图注册

# 初始化后端
bot_sql_init()
bot_init()

@app.route('/src/<path:path>')#网页的所有文件都是来自服务器
def send_image(path):
    return send_file(path, mimetype='image/jpeg')

@app.route('/')#访问的路径
def hello_world():
    return redirect('/welcome')#根路径开始，跳转登陆
    return 'Hello system!'

@app.route('/welcome', methods=['GET', 'POST'])#访问的路径
def welcome():
    if request.method == 'POST':
        return redirect('/procs')#未实现返回功能选项首页
    return render_template('home_page.html')


# 释放资源清理函数
def cleanup():
    # 释放资源
    print("退出，释放资源...")
    bot_quit()
    bot_sql_quit()
    print("成功退出！")
    pass

# 注册信号处理函数
def signal_handler(sig, frame):
    print(f'收到信号: {sig}, 关闭 Flask 应用')
    cleanup()  # 释放资源清理函数
    sys.exit(0)  # 退出程序

# 设置信号处理函数
signal.signal(signal.SIGINT, signal_handler)  # SIGINT 对应 Ctrl+C
signal.signal(signal.SIGTERM, signal_handler)  # SIGTERM 通常用于优雅地关闭程序

if __name__ == '__main__':
    app.run(debug=False)     # 阻塞


